home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2284 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Sat, 20 Jan 96 01:05:12 GMT
  6. Organization: none
  7. Message-ID: <822099912snz@genesis.demon.co.uk>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>  <4dorr8$i58@cloner3.netcom.com> <ALUN.CHAMPION.96Jan19170141@g7240065.bridge.bst.bls.com> <4dp8cr$sit@crl.crl.com>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <4dp8cr$sit@crl.crl.com> bobfry@crl.com "Robert Fry" writes:
  15.  
  16. >Someone was asking for a quick way to determine if a number is a power of 
  17. >2. The solutions I've seen involved ounting every bit and seeing if the 
  18. >number of 'on' bits is 1. But why not take advantage of the binary 
  19. >representation of numbers and use:
  20. >int is_power_of_2( long num)
  21.  
  22. Bill said he was using unsigned long ints which are better suited to this
  23. (it doesn't work when num is negative).
  24.  
  25. >{
  26. >    return((( num - 1) & num) == 0);
  27. >}
  28.  
  29. It is also important to consider the special case of 0. This classes it
  30. as a power of 2 which may or may not be what is wanted (or it may not
  31. matter).
  32.  
  33. >(You could also make a macro of it if you need better speed in exchange 
  34. >for reduced maintainability):
  35. >
  36. >#define IS_POWER_OF_2(num) (!(( num - 1) & num))
  37.  
  38. Best to fully parenthesize the macro arguments i.e.
  39.  
  40. #define IS_POWER_OF_2(num) (!((num)-1 & (num)))
  41.  
  42. >Be careful with this, of course. IS_POWER_OF_2(x++) has undefined results,
  43. >for example.
  44.  
  45. Right. Naming conventions have been regularly discussed on comp.lang.c.
  46. Maybe it would be a good idea to adopt a naming convention which
  47. clearly distinhuishes macros that are unsafe for side-effects.
  48.  
  49. -- 
  50. -----------------------------------------
  51. Lawrence Kirby | fred@genesis.demon.co.uk
  52. Wilts, England | 70734.126@compuserve.com
  53. -----------------------------------------
  54.